#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "msgq.h"
#include "tools.h"


Ctos ctos;
Stoc stoc;

Ctos ctos2;
Stoc stoc2;

void transf_acc(void)
{
	char path[PATH_MAX];
	sprintf(path,"%s/%u",ACC_PATH,ctos.acc.id);
	pf("acc path:%s\n",path);
	int fd = open(path,O_RDWR|O_EXCL,0644);
	if(ERROR == fd)
	{
		perror("open acc");
		strcpy(stoc.str,"服务器正在升级，请耐心等待...");
		stoc_send(&stoc);//返回消息
		return;
	}
	Account aco;
	read(fd,&aco,sizeof(aco));

	char path2[PATH_MAX];
	sprintf(path2,"%s/%u",ACC_PATH,ctos2.acc.id);
	pf("acc path2:%s\n",path2);
	int fd2 = open(path2,O_RDWR|O_EXCL,0644);
	if(ERROR == fd2)
	{
		perror("open acc");
		strcpy(stoc.str,"要转帐的卡号不存在！转帐失败！\n");
	}
	else if(ctos.acc.money > aco.money)
	{
		strcpy(stoc.str,"您的余额不足，转帐失败！\n");
	}
	else
	{
		Account aco2;
		read(fd2,&aco2,sizeof(aco2));
		ctos2.acc.money = aco2.money + ctos2.acc.money;
		lseek(fd,0,SEEK_SET);
		write(fd2,&ctos2.acc,sizeof(ctos2.acc));
		{
					ctos.acc.money = aco.money - ctos.acc.money;
					lseek(fd,0,SEEK_SET);
					write(fd,&ctos.acc,sizeof(ctos.acc));
					sprintf(stoc.str,"转帐成功！\n当前余额为：%f",ctos.acc.money);
		}
	}
	stoc_send(&stoc);//返回消息
}

int main()
{
	init_msgq();
	for(;;)
	{
		ctos_recv(&ctos,TYPE_TRANSF);
		ctos_recv(&ctos2,TYPE_TRANSF_TWO);
		stoc.type = ctos.pid;//反馈消息类型为进程号
		transf_acc();
	}
}


